package com.admin.web.controller;

import com.admin.bean.HttpResult;
import com.admin.model.AppUp;
import com.admin.repository.mongo.AppUpRepository;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSFile;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@RestController
@RequestMapping("/app/appUp")
public class AppUpController {
    @Resource
    private AppUpRepository appUpRepository;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private GridFsTemplate gridFsTemplate;

    /**
     * 获取最新版本号
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/findAppUpNew")
    public HttpResult<AppUp> findAppUpNew() throws Exception {
        Query query = new Query();
        Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "createTime"));
        Pageable pageable = new PageRequest(0, 1, sort);
        query.with(pageable);
        AppUp appUp = mongoTemplate.findOne(query, AppUp.class);
        return HttpResult.buildSuccess(appUp);
    }

    @RequestMapping("/save")
    @ResponseBody
    public HttpResult<String> save(@RequestParam(value = "file", required = false) MultipartFile file,
                                   AppUp appUp) throws IOException {
        DBObject metadata = new BasicDBObject();
        metadata.put("type", "wgt");

        GridFSFile gridFSFile = gridFsTemplate.store(file.getInputStream(), file.getName(), metadata);
        appUp.setFileId(gridFSFile.getId().toString());
        appUpRepository.save(appUp);
        return HttpResult.buildSuccess("保存成功");
    }
}
